package com.njym.java.security.app.rest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njym.java.security.app.biz.*;
import com.njym.java.security.app.entity.*;
import com.njym.java.security.common.constant.UserConstant;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.notify.NotifyService;
import com.njym.java.security.common.notify.NotifyType;
import com.njym.java.security.common.rest.BaseController;
import com.njym.java.security.common.service.CaptchaCodeManager;
import com.njym.java.security.common.util.CharUtil;
import com.njym.java.security.common.util.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("familyUser")
public class FamilyUserController extends BaseController<FamilyUserBiz, FamilyUser> {
    private final Log logger = LogFactory.getLog(UserRelationController.class);
    @Autowired
    private PlatformTransactionManager txManager;
    @Autowired
    private FamilyUserBiz familyUserBiz;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private FamilyUserGroupsBiz familyUserGroupsBiz;
    @Autowired
    private UserGroupsToUserBiz userGroupsToUserBiz;
    @Autowired
    private FamilyConfigBiz familyConfigBiz;
    @Autowired
    private UserBiz userBiz;
    @Autowired
    private FamilyWalletRecordBiz familyWalletRecordBiz;
    @Autowired
    private PaymentRecordBiz paymentRecordBiz;

    @Autowired
    private FamilyRelationshipBiz familyRelationshipBiz;

    @RequestMapping(value = "/clientId", method = RequestMethod.GET)
    @ResponseBody
    public Object getClientId(String userId,String cid) {
        if (!userId.equals("undefined")) {
            FamilyUser familyUser = new FamilyUser();
            familyUser.setId(Integer.parseInt(userId));
            familyUser.setAttr3(cid);
            baseBiz.updateSelectiveById(familyUser);
            return new ObjectRestResponse<>();
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 查询家庭成员
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryFamily",method = RequestMethod.GET)
    @ResponseBody
    public Object queryFamily(String id){
        if (!id.equals("undefined")) {
            Example example = new Example(FamilyUser.class);
            Example example1 = new Example(FamilyUser.class);
            Example example2 = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("id", Integer.parseInt(id));
            List<FamilyUser> user =  baseBiz.selectByExample(example);
            List<FamilyUser> family = null;
            if(user.get(0).getPid() == null){
                return new ObjectRestResponse<FamilyNews>().rel(true).data(-2);
            }
            if(user.get(0).getPid().equals(user.get(0).getId())){
                example1.createCriteria().andEqualTo("pid", id).andNotEqualTo("id", Integer.parseInt(id));
                family =  baseBiz.selectByExample(example1);
            }else{
                example2.createCriteria().andEqualTo("pid", user.get(0).getPid()).andNotEqualTo("id", Integer.parseInt(id));
                family =  baseBiz.selectByExample(example2);
            }
            Map<String, Object> data = new HashMap<>(2);
            data.put("list", family);
            return new ObjectRestResponse<FamilyNews>().rel(true).data(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }


    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<?> logout(String mobile ) {
        familyUserBiz.deluser(mobile);
        return   new ObjectRestResponse<>();
    }

    /**
     * 查询个人信息
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> getUserByMobile(String mobile){
        FamilyUser familyUser = familyUserBiz.getUserInfo(mobile);
        return new ObjectRestResponse<FamilyUser>().rel(true).data(familyUser);
    }

    /**
     * 获取统计页面代理总数
     * @return
     */
    @RequestMapping(value = "/getCount",method = RequestMethod.GET)
    @ResponseBody
    public Object getCount(){
        Integer count = baseBiz.getDailiCounts("");
        return new ObjectRestResponse<>().data(count);
    }

    /**
     * 获取统计页面列表
     * @param flag
     * @param limit
     * @param page
     * @return
     */
    @RequestMapping(value = "/getTheList",method = RequestMethod.GET)
    @ResponseBody
    public Object getTheList(Integer flag, Integer limit, Integer page, String name){
        Map<String,Object> data = new HashMap<>(2);
        Integer counts = baseBiz.getDailiCounts(name);
//        Page<Object> result = PageHelper.startPage(page,limit);
        if (flag == 1) {    //课程销售量
            List<PaymentRecordVo> list = paymentRecordBiz.getTotalsByPerson(page,limit,name);
            data.put("rows",list);
        }else {     //会员注册量
            List<FamilyUserVo> list = baseBiz.queryDaiLiRegister(page,limit,name);
            data.put("rows",list);
        }
        data.put("total",Math.ceil(counts/limit));
        return new ObjectRestResponse<>().data(data);
    }

    /**
     * 获取统计页面uchart所需信息
     * @param flag
     * @return
     */
    @RequestMapping(value = "/getServerData",method = RequestMethod.GET)
    @ResponseBody
    public Object getServerData(Integer flag){
        Map<String,Object> data = new HashMap<>(2);
        List<Object> series = new ArrayList();
        Map<String,Object> map1 = new HashMap<>(2);
        Map<String,Object> map2 = new HashMap<>(2);

        if (flag == 1) {    //课程总销售量
            BigDecimal total = new BigDecimal(paymentRecordBiz.getTotals().toString());    //总额度
            BigDecimal dailis = new BigDecimal(paymentRecordBiz.getDailis().toString());   //代理所属额
            data.put("total",total);

            map1.put("name","发起人销售量");
            map1.put("data",dailis);
            series.add(map1);
            map2.put("name","其他");
            map2.put("data",total.subtract(dailis).doubleValue());
            series.add(map2);
        }else {     //软件注册量
            Integer total = baseBiz.getAllUserCounts(); //总注册
            Integer dailis = baseBiz.getDailiUserCounts();  //代理发展下级数量
            data.put("total",total);

            map1.put("name","由发起人邀请");
            map1.put("data",dailis);
            series.add(map1);
            map2.put("name","其他");
            map2.put("data",total - dailis);
            series.add(map2);
        }
        data.put("series",series);
        return new ObjectRestResponse<>().rel(true).data(data);
    }

    /**
     * 修改密码
     * @param mobile
     * @param oldPassword
     * @param newPassword
     * @param renewPassword
     * @return
     */
    @RequestMapping(value = "/updatemypwd", method = RequestMethod.GET)
    @ResponseBody
    public Object updatemypwd(String mobile, String oldPassword, String newPassword, String renewPassword){
        //  查询手机用户
        FamilyUser userInfo = familyUserBiz.getUserByMobile(mobile);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //  判断旧密码与登陆的密码是否一致
        if(!encoder.matches(oldPassword, userInfo.getPassword())){
            return  ResponseUtil.fail(403,"旧密码错误");
        }
        //  旧密码和新密码不能一样
        if(oldPassword.equals(newPassword)){
          return ResponseUtil.fail(403,"旧密码和新密码不能一样");
        }
        // 判断两次输入的新密码是否一致
        if(!newPassword.equals(renewPassword)) {
            return ResponseUtil.fail(403, "新密码不一致");
        }
        String newPasswords = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(newPassword);
        userInfo.setPassword(newPasswords);
        baseBiz.updateById(userInfo);
        return ResponseUtil.ok();

    }

    /**
     * 修改个人信息
     * @param mobile
     * @param choose
     * @param avatar
     * @param nickName
     * @param attr2
     * @return
     */
    @RequestMapping(value = "/updateuserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Object updateUserInfo(String mobile, Integer choose, String avatar, String nickName, String attr2,Integer dignity){
        //  查询手机用户
        familyUserBiz.deluser(mobile);
        FamilyUser userInfo = familyUserBiz.getUserByMobile(mobile);
        if(choose == 0){
            // 头像
            userInfo.setAvatar(avatar);
        }else if(choose == 1){
            // 昵称
            userInfo.setNickName(nickName);
        }else if(choose == 2){
            // 生日
            userInfo.setAttr2(attr2);

        }else if (choose == 4){
            // 主家庭
            if(dignity == 0){
                userInfo.setPid(userInfo.getId());
            }else {
                userInfo.setPid(null);
            }
        } else {
            userInfo.setMobile(mobile);
        }
        baseBiz.updateById(userInfo);
        return  ResponseUtil.ok(userInfo);

    }

    /**
     * 修改手机号码
     * @param mobile
     * @param oldmobile
     * @param newmobile
     * @param usercode
     * @return
     */
    @RequestMapping(value = "/updateMobile", method = RequestMethod.GET)
    @ResponseBody
    public Object updateMobile(String mobile,String oldmobile,String newmobile,String usercode){

        FamilyUser familyUser = familyUserBiz.getUserByMobile(mobile);
        // 判断旧手机是否输入正确
        if(!familyUser.getMobile().equals(oldmobile)){
            return ResponseUtil.fail(-1, "旧手机号码错误");
        }
        //  判断旧手机与新手机是否一致
        if(oldmobile.equals(newmobile)){
            return ResponseUtil.fail(-1, "新旧手机号码不能一致");
        }
        //判断验证码是否正确
        if(usercode != null){
            //判断验证码是否正确
            String cacheCode = CaptchaCodeManager.getCachedCaptcha(newmobile);
            if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(usercode)) {
                return ResponseUtil.fail(-1, "验证码错误");
            }
        }
        // 查找新手机用户是否已注册
        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("mobile",newmobile);
        List<FamilyUser> list  =  familyUserBiz.selectByExample(example);
        if(list.size() >0){
            return ResponseUtil.fail(-1, "用户已经注册！");
        }
        familyUser.setMobile(newmobile);
        familyUserBiz.updateById(familyUser);
        return ResponseUtil.ok();
    }


    /**
     * 发送验证码
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    @ResponseBody
    public Object sendcCode(String mobile ) {

        String code = CharUtil.getRandomNum(6);
        String params = new String("{\"code\":\"" + code + "\"}");
        notifyService.notifySmsTemplateSync(mobile, NotifyType.REGISTER, params);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean successful = CaptchaCodeManager.addToCache(mobile, code);
        return successful ? ResponseUtil.ok() : ResponseUtil.badArgument();
    }



    /**
     * 注册
     * @param username
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    @ResponseBody
    public Object register(String username,String relation,String userphone,String userpass,String usercode, Boolean dignity, String fuserId) {
        //判断验证码是否正确
        if(usercode != null){
            //判断验证码是否正确
            String cacheCode = CaptchaCodeManager.getCachedCaptcha(userphone);
            if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(usercode)) {
                return ResponseUtil.fail(-1, "验证码错误");
            }
        }

        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("mobile",userphone);
        List<FamilyUser> list  =  familyUserBiz.selectByExample(example);
        if(list.size() >0){
            return ResponseUtil.fail(-1, "用户已经注册！");
        }
        FamilyUser familyUser  = new FamilyUser();
        familyUser.setMobile(userphone);
        familyUser.setName(username);
        familyUser.setRelation(relation);
        familyUser.setNickName(username);
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(userpass);
        familyUser.setPassword(password);
        familyUser.setCreatedTime(new Date());
        familyUser.setFamilyFlag(0);
        familyUser.setClubFlag(0);
        familyUser.setSex(0);
        familyUser.setIntegral(0);
        familyUser.setPrice(0.00);
        familyUser.setAttr2("1970-01-01");
        familyUser.setAvatar("https://jiatingjianshe.oss-cn-beijing.aliyuncs.com/touxiang.png");

        //判断是代理还是家庭邀请
        if(fuserId != null && fuserId != "" && !"undefined".equals(fuserId)) {
            fuserId = fuserId.toUpperCase();
            familyUser.setFuserId(fuserId);
            if ("D".equals(fuserId.substring(0, 1))) {
                familyUser.setBaseId(fuserId);
                //查询baseuser信息
                Example example4 = new Example(User.class);
                example4.createCriteria().andEqualTo("attr4", fuserId);

                List<User> baseusers = userBiz.selectByExample(example4);
                if (baseusers.size() > 0) {
                    User u = baseusers.get(0);
                    familyUser.setTeacherId(u.getId());
                }

            }else
            if ("J".equals(fuserId.substring(0, 1))) {
                Example example1 = new Example(FamilyUser.class);
                example1.createCriteria().andEqualTo("generalizeCode", fuserId);
                List<FamilyUser> users = familyUserBiz.selectByExample(example1);
                if (users.size() > 0) {
                    familyUser.setBaseId(users.get(0).getBaseId());
                    Example example4 = new Example(User.class);
                    example4.createCriteria().andEqualTo("attr4", users.get(0).getBaseId());

                    List<User> baseusers = userBiz.selectByExample(example4);
                    if (baseusers.size() > 0) {
                        User u = baseusers.get(0);
                        familyUser.setTeacherId(u.getId());
                    }
                }else{
                    return ResponseUtil.fail(-1, "邀请码错误");
                }

            }else{
                return ResponseUtil.fail(-1, "邀请码错误");
            }
        }
        //生成邀请码并判断是否重复
        for(int i = 0; ; i ++) {
            String code = "J" + genRandomNum();
            Example example2 = new Example(FamilyUser.class);
            example2.createCriteria().andEqualTo("generalizeCode", code);
            List<FamilyUser> fu = familyUserBiz.selectByExample(example2);
            if (fu.size() == 0) {
                familyUser.setGeneralizeCode(code);
                break;
            }
        }

        List<FamilyConfig> dlCon = null;
        List<FamilyConfig> jtCon = null;
        List<User> baseuser = null;
        List<FamilyUser> familyuser = null;

        Example example11 = new Example(User.class);
        example11.createCriteria().andEqualTo("mobilePhone", userphone).andEqualTo("identity", 1).andEqualTo("attr5", 1);
        List<User> base = userBiz.selectByExample(example11);
        if(base.size() == 1){
            familyUser.setTeacherId(base.get(0).getId());
            familyUser.setFuserId(base.get(0).getAttr4());
            familyUser.setBaseId(base.get(0).getAttr4());
        }

        int userid =   familyUserBiz.insertFamilyUser(familyUser);


//        if(dignity){
//            familyUser.setPid(familyUser.getId());
//            familyUser.setId(familyUser.getId());
//            familyUserBiz.updateById(familyUser);
//        }
        if(userid == 1){


            //代理邀请注册
            if(fuserId != null && fuserId != "" && !"undefined".equals(fuserId)) {
                if ("D".equals(fuserId.substring(0, 1))) {

                    //查询baseuser信息
                    Example example4 = new Example(User.class);
                    example4.createCriteria().andEqualTo("attr4", fuserId);

                    baseuser = userBiz.selectByExample(example4);
                    if (baseuser.size() > 0) {
                        User u = baseuser.get(0);
                        familyUser.setTeacherId(u.getId());
                    }
                }
                //家庭邀请注册后返还积分
                if ("J".equals(fuserId.substring(0, 1))) {
                    //先返还积分
                    //查询该返还多少积分
                    Example example6 = new Example(FamilyConfig.class);
                    example6.createCriteria().andEqualTo("id", 10000002);
                    jtCon = familyConfigBiz.selectByExample(example6);
                    //查询familyuser信息并修改积分
                    Example example7 = new Example(FamilyUser.class);
                    example7.createCriteria().andEqualTo("generalizeCode", fuserId);
                    familyuser = familyUserBiz.selectByExample(example7);
                    if (familyuser.size() > 0) {
                        Integer jyJiFen = Integer.parseInt(jtCon.get(0).getValue());
                        FamilyUser u = familyuser.get(0);
                        if (u.getIntegral() == null) {
                            u.setIntegral(jyJiFen);
                        } else {
                            u.setIntegral(u.getIntegral() + jyJiFen);
                        }

                        //添加返还积分记录
                        FamilyWalletRecord familyWalletRecord = new FamilyWalletRecord();
                        familyWalletRecord.setUserId(familyUser.getId());
                        familyWalletRecord.setMechaismId(u.getId());
                        familyWalletRecord.setType(2);
                        familyWalletRecord.setDetail(jyJiFen);
                        familyWalletRecord.setLeftPoints(u.getIntegral() + jyJiFen);
                        familyWalletRecord.setModifyTime(new Date());
                        familyWalletRecord.setRecordSn("家庭邀请注册返还邀请人积分");


                        // 开启事务管理
                        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                        TransactionStatus status = txManager.getTransaction(def);
                        try {
                            //修改积分
                            familyUserBiz.updateById(u);
                            //添加返积分记录
                            familyWalletRecordBiz.insert(familyWalletRecord);

                        }catch (Exception ex) {
                            txManager.rollback(status);
                            logger.error("网络连接超时", ex);
                            return   ResponseUtil.fail(-1,"网络连接超时,注册失败！");
                        }
                        txManager.commit(status);

                        //发送推广人信息
                        //发送短信通知
                        String params = new String("{\"tel\":\"" + userphone + "\",\"time\":\"" + new Date() + "\",\"integral\":\"" + jyJiFen + "\"}");
                        notifyService.notifySmsTemplateSync(u.getMobile(), NotifyType.NINGDING, params);

                    }
                }
            }

            return   ResponseUtil.ok();
        }else{
            return   ResponseUtil.fail(-1,"注册失败！");
        }
    }

    /**
     * 生成邀请码
     * @return
     */
    public String genRandomNum(){
        int  maxNum = 36;
        int i;
        int count = 0;
        char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while(count < 5){
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count ++;
            }
        }
        return pwd.toString();
    }

    /**
     * 注册
     * @param username
     * @return
     */
    @RequestMapping(value = "/addFamily", method = RequestMethod.GET)
    @ResponseBody
    public Object addFamily(String username,String relation,Integer familyId,String userphone,String userpass,String usercode) {
        //判断验证码是否正确
        if(usercode != null){
            //判断验证码是否正确
            String cacheCode = CaptchaCodeManager.getCachedCaptcha(userphone);
            if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(usercode)) {
                return ResponseUtil.fail(-1, "验证码错误");
            }
        }

        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("mobile",userphone);
        List<FamilyUser> list  =  familyUserBiz.selectByExample(example);
        if(list.size() >0){
            return ResponseUtil.fail(-1, "用户已经注册！");
        }
        FamilyUser familyUser  = new FamilyUser();
        familyUser.setMobile(userphone);
        familyUser.setName(username);
//        familyUser.setPid(pid);
        familyUser.setRelation(relation);
        familyUser.setNickName(username);
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(userpass);
        familyUser.setPassword(password);
        familyUser.setCreatedTime(new Date());
        familyUser.setFamilyFlag(0);
        familyUser.setClubFlag(0);
        familyUser.setSex(0);
        familyUser.setAttr2("1970-01-01");
        familyUser.setAvatar("https://jiatingjianshe.oss-cn-beijing.aliyuncs.com/touxiang.png");
        int num =   familyUserBiz.insertFamilyUser(familyUser);

        if(num !=0){
            //添加家庭成员
            FamilyRelationship familyRelationship = new FamilyRelationship();
            familyRelationship.setDeleted(0);
            familyRelationship.setFamilyTypeId(familyId);
            familyRelationship.setRelationName(relation);
            familyRelationship.setUserId(familyUser.getId());
            familyRelationshipBiz.insert(familyRelationship);

//            Example example1 = new Example(FamilyUserGroups.class);
//            example1.createCriteria().andEqualTo("usAdminId", pid).andEqualTo("isFamily", 1);
//            List<FamilyUserGroups> groups = familyUserGroupsBiz.selectByExample(example1);
//            familyUserGroupsBiz.updateNum(pid);
//            UserGroupsToUser userGroupsToUser = new UserGroupsToUser();
//            userGroupsToUser.setUserId(userid);
//            userGroupsToUser.setGroupId(groups.get(0).getId());
//            userGroupsToUser.setCreateTime(new Date());
//            userGroupsToUser.setGroupNick(username);
//            userGroupsToUserBiz.insertSelective(userGroupsToUser);
            return   ResponseUtil.ok();
        }else{
            return   ResponseUtil.fail(-1,"注册失败！");
        }

    }


    /**
     * 获取家庭成员
     * @param familyId
     * @return
     */
    @RequestMapping(value = "/getFamilyUser", method = RequestMethod.GET)
    @ResponseBody
    public Object getFamilyUser(Integer familyId ) {
        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("pid",familyId);
        example.setOrderByClause("relation");
        List<FamilyUser> list = baseBiz.selectByExample(example);
        return   ResponseUtil.ok(list);
    }



    @RequestMapping(value = "/getfamilyByid", method = RequestMethod.GET)
    @ResponseBody
    public Object getfamilyByid(String familyId ) {
        if (!familyId.equals("undefined")) {
            FamilyUser familyUser = baseBiz.selectById(Integer.parseInt(familyId));
            return   ResponseUtil.ok(familyUser);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }

    /**
     * 查询成员
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/getUserBymobile", method = RequestMethod.GET)
    @ResponseBody
    public Object getUserBymobile(String mobile ) {
        FamilyUser user =    baseBiz.getUserByMobile(mobile);
        return   ResponseUtil.ok(user);
    }

    @RequestMapping(value = "/queryDaiLi", method = RequestMethod.GET)
    @ResponseBody
    public Object queryDaiLi(String id, String start, String end, String phone, Integer order, Integer isPay,
        @RequestParam(value = "pages", defaultValue = "1") Integer pages,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        if (!id.equals("undefined")) {
            Integer ids = Integer.parseInt(id);
            String startDate = "";
            String endDate = "";

            Example example = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("id", ids);
            List<FamilyUser> list = baseBiz.selectByExample(example);


            if(start != "" && end != ""){
                startDate = start + " 00:00:00";
                endDate = end + " 23:59:59";
            }



            List<FamilyUserVo> user = baseBiz.queryDaiLi(list.get(0).getGeneralizeCode(),ids, list.get(0).getBaseId(),phone, startDate, endDate,pages, limit, order, isPay);

            long total = PageInfo.of(user).getTotal();
            int totalPages = (int) Math.ceil((double) total / limit);

            long theTotal = baseBiz.getTotal_2(list.get(0).getBaseId(), ids, list.get(0).getGeneralizeCode());
            long hasPay = baseBiz.countHasPay_2(list.get(0).getBaseId(), list.get(0).getGeneralizeCode());
            long notPay = theTotal - hasPay;
            Map<String, Object> data = new HashMap<>(5);
            data.put("list", user);
            data.put("total", theTotal);
            data.put("hasPay", hasPay);
            data.put("notPay", notPay);
            data.put("totalPages", totalPages);

            return   ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    @RequestMapping(value = "/queryIsDaiLi", method = RequestMethod.GET)
    @ResponseBody
    public Object queryIsDaiLi(String mobile ) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("mobilePhone", mobile).andEqualTo("attr5", 1);
        List<User> user = userBiz.selectByExample(example);
        if (user.size() > 0){
            if ("1".equals(user.get(0).getIdentity())){
                return ResponseUtil.ok(user.get(0).getId());
            }else {
                return ResponseUtil.fail();
            }
        }else{
            return ResponseUtil.fail();
        }
    }

    /**
     * 查询成员
     * @param
     * @return
     */
    @RequestMapping(value = "/inviteUser", method = RequestMethod.GET)
    @ResponseBody
    public Object inviteUser(String id,String familyId ,String relation) {
        if (!id.equals("undefined") && !familyId.equals("undefined")) {
            FamilyRelationship familyRelationship = new FamilyRelationship();
            familyRelationship.setDeleted(0);
            familyRelationship.setFamilyTypeId(Integer.parseInt(familyId));
            familyRelationship.setRelationName(relation);
            familyRelationship.setUserId(Integer.parseInt(id));
            familyRelationshipBiz.insert(familyRelationship);
            return   ResponseUtil.ok();
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

//        Example example = new Example(FamilyUserGroups.class);
//        example.createCriteria().andEqualTo("usAdminId", pid).andEqualTo("isFamily", 1);
//        List<FamilyUserGroups> groups = familyUserGroupsBiz.selectByExample(example);
//
//
//        familyUserGroupsBiz.updateNum(pid);
//
//
//        UserGroupsToUser userGroupsToUser = new UserGroupsToUser();
//        userGroupsToUser.setUserId(id);
//        userGroupsToUser.setGroupId(groups.get(0).getId());
//        userGroupsToUser.setCreateTime(new Date());
//        userGroupsToUser.setGroupNick(user.getNickName());
//
//        userGroupsToUserBiz.insertSelective(userGroupsToUser);
    }


    /**
     * 修改手势密码
     * @param
     * @return
     */
    @RequestMapping(value = "/setSignal", method = RequestMethod.GET)
    @ResponseBody
    public Object setSignal(String signal ,String type ,String id) {
        if (!id.equals("undefined")) {
            FamilyUser user =  baseBiz.selectById(Integer.parseInt(id));
            user.setAttr4(type);
            user.setAttr5(signal);
            baseBiz.updateById(user);
            return   ResponseUtil.ok(user);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }

    }


    /**
     * 忘记密码
     * @param
     * @return
     */
    @RequestMapping(value = "/updatePas", method = RequestMethod.GET)
    @ResponseBody
    public Object updatePas(String userphone,String userpass,String usercode) {
        //判断验证码是否正确
        if(usercode != null){
            //判断验证码是否正确
            String cacheCode = CaptchaCodeManager.getCachedCaptcha(userphone);
            if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(usercode)) {
                return ResponseUtil.fail(-1, "验证码错误");
            }
        }

        FamilyUser user =  baseBiz.getUserByMobile(userphone);
        if(user!=null){
            String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(userpass);
            user.setPassword(password);
            baseBiz.updateById(user);
            return   ResponseUtil.ok(user);
        }else{
            return   ResponseUtil.fail(-1 , "该手机用户不存在！");
        }

    }




    /**
     * 删除家庭成员
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteFamilyUser", method = RequestMethod.GET)
    @ResponseBody
    public Object deleteFamilyUser(String id) {
        if (!id.equals("undefined")) {
            FamilyUser user =  baseBiz.selectById(Integer.parseInt(id));
            user.setPid(null);
            baseBiz.updateById(user);
            return   ResponseUtil.ok(user);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    @RequestMapping(value = "/getTotalPopular", method = RequestMethod.GET)
    @ResponseBody
    public Object getTotalPopular(String id){
        if (!id.equals("undefined")) {
            Integer ids = Integer.parseInt(id);
            Example example = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("id", ids);
            List<FamilyUser> list = baseBiz.selectByExample(example);

            long totalPopular  = baseBiz.getTotalPopular(ids, list.get(0).getBaseId());
            Map<String, Object> data = new HashMap<>(1);
            data.put("totalPopular", totalPopular);
            return   ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    /**
     * 查询代理直接邀请会员
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryDaiLiUser", method = RequestMethod.GET)
    @ResponseBody
    public Object queryDaiLiUser(String id, String start, String end, String phone, Integer order, Integer isPay,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit) throws ParseException {
        if (!id.equals("undefined")) {
            Integer ids = Integer.parseInt(id);
            String startDate = "";
            String endDate = "";

            Example example = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("id", ids);
            List<FamilyUser> list = baseBiz.selectByExample(example);

            Example example1 = new Example(FamilyUser.class);

            if(start != "" && end != "") {
                startDate = start + " 00:00:00";
                endDate = end + " 23:59:59";

            }


            List<FamilyUserVo> user = baseBiz.queryDaiLiUser(list.get(0).getGeneralizeCode(), ids, phone, startDate, endDate, page, limit, order, isPay);
            long total = PageInfo.of(user).getTotal();
            int totalPages = (int) Math.ceil((double) total / limit);

            long theTotal = baseBiz.getTotal(list.get(0).getGeneralizeCode(), ids);
            long hasPay = baseBiz.countHasPay(list.get(0).getGeneralizeCode());
            long notPay = theTotal - hasPay;
            Map<String, Object> data = new HashMap<>(5);
            data.put("list", user);
            data.put("total", theTotal);
            data.put("hasPay", hasPay);
            data.put("notPay", notPay);
            data.put("totalPages", totalPages);

            return   ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    /**
     * 查询代理直接邀请会员
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryDaiLiUsers", method = RequestMethod.GET)
    @ResponseBody
    public Object queryDaiLiUsers(String id, String name,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        if (!id.equals("undefined")) {
            Integer ids = Integer.parseInt(id);
            Example example = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("id", ids);
            List<FamilyUser> list = baseBiz.selectByExample(example);

            Example example1 = new Example(FamilyUser.class);
            if(name == null || "".equals(name)) {
                example1.createCriteria().andEqualTo("fuserId", list.get(0).getGeneralizeCode()).andNotEqualTo("id", ids);
            }else{
                example1.createCriteria().andEqualTo("fuserId", list.get(0).getGeneralizeCode()).andNotEqualTo("id", ids).andLike("name", "%" + name + "%");
            }
            example1.setOrderByClause("created_time DESC");

            PageHelper.startPage(page, limit);
            List<FamilyUser> user = baseBiz.selectByExample(example1);

            long total = PageInfo.of(user).getTotal();
            int totalPages = (int) Math.ceil((double) total / limit);
            Map<String, Object> data = new HashMap<>(3);
            data.put("list", user);
            data.put("total", total);
            data.put("totalPages", totalPages);

            return   ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }


    @RequestMapping(value = "/queryJianJie", method = RequestMethod.GET)
    @ResponseBody
    public Object queryTeacherDetail(String code) throws Exception {

            Example example = new Example(FamilyUser.class);
            example.createCriteria().andEqualTo("fuserId", code);
            List<FamilyUser> zhijie = baseBiz.selectByExample(example);
            int num = this.count(zhijie, zhijie.size());
            Map<String, Object> data = new HashMap<>(3);
            data.put("count", num);
            data.put("zhijie", zhijie.size());
            return ResponseUtil.ok(data);

    }

    public int count(List<FamilyUser> fu, int counts) throws Exception {
        int  countnum = counts;
        if(fu.size() == 0){
            return counts;
        }
        //间接会员列表,查询三级总人数
        List<FamilyUser> jian1;
        List list = new ArrayList<>();
        for (int i = 0; i < fu.size(); i++){
            list.add(fu.get(i).getGeneralizeCode()) ;
        }
        Example example1 = new Example(FamilyUser.class);
        example1.createCriteria().andIn("fuserId", list);
        jian1 = baseBiz.selectByExample(example1);
        countnum = countnum + jian1.size();
        return countnum;
    }



    @RequestMapping(value = "/queryDaiLiDetail", method = RequestMethod.GET)
    @ResponseBody
    public Object queryDaiLiDetail(String userId, String start, String end, String phone,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        if (!"undefined".equals(userId)) {
            Integer uid = Integer.parseInt(userId);

            String startDate = "";
            String endDate = "";
            if(start != ""){
                startDate = start + " 00:00:00";
            }
            if(end != ""){
                endDate = end + " 23:59:59";
            }

            List<FamilyWalletRecordVo> list = familyWalletRecordBiz.queryDaiLiDetail(uid, page, limit, startDate, endDate, phone);
            long total = PageInfo.of(list).getTotal();
            int totalPages = (int) Math.ceil((double) total / limit);
            Map<String, Object> data = new HashMap<>(3);
            data.put("list", list);
            data.put("total", total);
            data.put("totalPages", totalPages);

            return ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    @RequestMapping(value = "/queryTeacherDetail", method = RequestMethod.GET)
    @ResponseBody
    public Object queryTeacherDetail(String userId,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        if (!"undefined".equals(userId)) {
            Integer uid = Integer.parseInt(userId);
            List<FamilyWalletRecordVo> list = familyWalletRecordBiz.queryTeacherDetail(uid, page, limit);
            long total = PageInfo.of(list).getTotal();
            int totalPages = (int) Math.ceil((double) total / limit);
            Map<String, Object> data = new HashMap<>(3);
            data.put("list", list);
            data.put("total", total);
            data.put("totalPages", totalPages);

            return ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    @RequestMapping(value = "/queryTeacherDetail_2", method = RequestMethod.GET)
    @ResponseBody
    public Object queryTeacherDetail_2(String userId, String start, String end, String phone,
                                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        if (!"undefined".equals(userId)) {
            Integer uid = Integer.parseInt(userId);
            String startDate = null;
            String endDate = null;
            if(start != "" && end != ""){
                startDate = start + " 00:00:00";
                endDate = end + " 23:59:59";
            }
            List<FamilyWalletRecordVo> list = familyWalletRecordBiz.queryTeacherDetail_2(uid, page, limit, startDate, endDate, phone);
            long total = PageInfo.of(list).getTotal();
            int totalPages = (int) Math.ceil((double) total / limit);
            Map<String, Object> data = new HashMap<>(3);
            data.put("list", list);
            data.put("total", total);
            data.put("totalPages", totalPages);

            return ResponseUtil.ok(data);
        } else {
            return ResponseUtil.fail(40301, "错误！");
        }
    }

    /**
     * 查询我的积分
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/myIntegral",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<FamilyUser> getIntegral(String mobile){
        FamilyUser familyUser = familyUserBiz.all(mobile);
        return new ObjectRestResponse<FamilyUser>().rel(true).data(familyUser);
    }

    @RequestMapping(value = "/queryNum",method = RequestMethod.GET)
    @ResponseBody
    public Object queryNum(String fuserId){
        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("fuserId", fuserId);
        List<FamilyUser> list = baseBiz.selectByExample(example);
        long total = PageInfo.of(list).getTotal();

        return ResponseUtil.ok(total);
    }
}